import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {
  notification,
  Row,
  Col,
  Card,
  Form,
  Icon,
  Select,
  Button,
  Input,
  Modal,
  DatePicker,
  Upload,
  message,
  Divider,
  Popconfirm,
  Spin,
  Alert,
  Tabs,
} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Person.less';
import {getNation} from '../../common/nation'

const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');


const CreateForm = Form.create({
  onValuesChange(props, changedFields) {
    props.onModelChange(changedFields);
  },
  mapPropsToFields(props) {
    const {formValues} = props;
    if (formValues) {
      return {
        id: Form.createFormField({
          value: formValues.id,
        }),
        name: Form.createFormField({
          value: formValues.name,
        }),
        sex: Form.createFormField({
          value: formValues.sex,
        }),
        idtype: Form.createFormField({
          value: formValues.idtype,
        }),
        idnum: Form.createFormField({
          value: formValues.idnum,
        }),
        nation: Form.createFormField({
          value: formValues.nation,
        }),
        birthday: Form.createFormField({
          value: formValues.birthday && moment(formValues.birthday, 'YYYY-MM-DD'),
        }),
        fzrq: Form.createFormField({
          value: formValues.fzrq && moment(formValues.fzrq, 'YYYY-MM-DD'),
        }),
        yxq: Form.createFormField({
          value: formValues.yxq && moment(formValues.yxq, 'YYYY-MM-DD'),
        }),
        avatar: Form.createFormField({
          value: formValues.avatar,
        }),
        mobile: Form.createFormField({
          value: formValues.mobile,
        }),
        address: Form.createFormField({
          value: formValues.address,
        }),

        fzjg: Form.createFormField({
          value: formValues.fzjg,
        }),
        place: Form.createFormField({
          value: formValues.place,
        }),
        political: Form.createFormField({
          value: formValues.political,
        }),
        education: Form.createFormField({
          value: formValues.education,
        }),
        medical: Form.createFormField({
          value: formValues.medical,
        }),
        emergencycontact: Form.createFormField({
          value: formValues.emergencycontact,
        }),
        contactmobile: Form.createFormField({
          value: formValues.contactmobile,
        }),
        worktype: Form.createFormField({
          value: formValues.worktype,
        }),
        workday: Form.createFormField({
          value: formValues.workday,
        }),
      };
    }
  },
})(props => {
  const {
    modalVisible, form, handleAdd, handleModalVisible, modalTitle, autoMessage, autoLoading, handleReadCard
  } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  return (
    <Modal
      width={920}
      visible={modalVisible}

      footer={modalTitle === '自动读卡' ? null :
        <span>
          <Button onClick={() => handleModalVisible()}>取消</Button>
          <Button type="primary" onClick={okHandle}>确定</Button>
        </span>}
      onCancel={() => handleModalVisible()}>


      <Tabs type="card" size="small">
        <TabPane tab="基本信息" key="1">
          <Spin spinning={autoLoading}>
            <Card title="身份证信息"
                  extra={modalTitle === '新增劳务人员' &&
                  <Button onClick={() => handleReadCard()} icon="idcard" size="small">读卡</Button>}
                  type="inner">
              <Row type="flex" justify="space-around" align="middle">
                <Col span={4}>
                  <FormItem>
                    {form.getFieldDecorator('id')(<span/>)}
                  </FormItem>
                  <FormItem>
                    {form.getFieldDecorator('avatar')(
                      <Upload disabled
                              action="/upload.do"
                              listType="picture-card"
                              className="avatar-uploader"
                              showUploadList={false}>
                        {form.getFieldValue('avatar') ?
                          <img src={`data:image/jpeg;base64,${form.getFieldValue('avatar')}`} alt="照片"/> :
                          <div>
                            <Icon type='plus'/>
                            <div className="ant-upload-text">照片</div>
                          </div>}
                      </Upload>)
                    }
                  </FormItem>
                </Col>
                <Col span={20}>
                  <Row>
                    <Col span={8}>
                      <FormItem labelCol={{span: 9}} wrapperCol={{span: 15}} label="姓名">
                        {form.getFieldDecorator('name', {
                          rules: [{required: true, message: '请输入姓名'}],
                        })(<Input style={{width: 120}} readOnly/>)}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem labelCol={{span: 8}} wrapperCol={{span: 10}} label="性别">
                        {form.getFieldDecorator('sex', {
                          rules: [{required: true, message: '请选择性别'}],
                        })(
                          <Select style={{width: 120}} placeholder="请选择" disabled>
                            <Select.Option value={1}>男</Select.Option>
                            <Select.Option value={0}>女</Select.Option>
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem labelCol={{span: 5}} wrapperCol={{span: 10}} label="民族">
                        {form.getFieldDecorator('nation', {
                          rules: [{required: true, message: '请选择民族'}],
                        })(
                          <Select style={{width: 120}} placeholder="请选择" showSearch disabled>
                            {getNation().map(d => <Select.Option key={d.name}>{d.name}</Select.Option>)}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={8}>
                      <FormItem labelCol={{span: 9}} wrapperCol={{span: 15}} label="出生日期">
                        {form.getFieldDecorator('birthday', {
                          rules: [{type: 'object', required: true, message: '请选择出生日期'}],
                        })(
                          <DatePicker placeholder="请选择" style={{width: 120}} disabled/>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem labelCol={{span: 8}} wrapperCol={{span: 16}} label="证件类型">
                        {form.getFieldDecorator('idtype', {
                          rules: [{required: true, message: '请选择证件类型',}]
                        })(
                          <Select style={{width: 120}} placeholder="请选择" disabled>
                            <Select.Option value={0}>身份证</Select.Option>
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={8} pull={1}>
                      <FormItem labelCol={{span: 8}} wrapperCol={{span: 16}} label="证件编号">
                        {form.getFieldDecorator('idnum', {
                          rules: [{required: true, message: '请输入证件编号'}],
                        })(<Input style={{width: 170}} readOnly/>)}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={8}>
                      <FormItem labelCol={{span: 9}} wrapperCol={{span: 15}} label="期限起始">
                        {form.getFieldDecorator('fzrq', {
                          rules: [{required: true, message: '请选择期限起始日期'}],
                        })(
                          <DatePicker placeholder="请选择" style={{width: 120}} disabled/>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem labelCol={{span: 8}} wrapperCol={{span: 15}} label="期限失效">
                        {form.getFieldDecorator('yxq', {
                          rules: [{required: true, message: '请选择期限失效日期'}],
                        })(
                          <DatePicker style={{width: 120}} disabled/>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={8} pull={1}>
                      <FormItem labelCol={{span: 8}} wrapperCol={{span: 15}} label="发证机关">
                        {form.getFieldDecorator('fzjg', {
                          rules: [{required: true, message: '请输入家庭住址'}],
                        })(<Input style={{width: 170}} readOnly/>)}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}} label="家庭住址">
                      {form.getFieldDecorator('address', {
                        rules: [{required: true, message: '请输入家庭住址'}],
                      })(<Input style={{width: '80%'}} readOnly/>)}
                    </FormItem>
                  </Row>
                </Col>
              </Row>
            </Card>
          </Spin>
          {modalTitle !== '自动读卡' && <Card style={{marginTop: 16}} title="其他信息" type="inner">

            <Row gutter={4}>
              <Col span={8}>
                <FormItem labelCol={{span: 10}} label="电话号码">
                  {form.getFieldDecorator('mobile', {
                    rules: [{
                      required: false, message: '请输入电话号码', pattern: /^1\d{10}$/,
                    }],
                  })(<Input style={{width: 120}} placeholder="请输入"/>)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{span: 10}} label="政治面貌">
                  {form.getFieldDecorator('political')(<Input style={{width: 120}} placeholder="请输入"/>)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{span: 10}} label="学历">
                  {form.getFieldDecorator('education')(
                    <Select style={{width: 120}} placeholder="请选择">
                      <Select.Option value="小学">小学</Select.Option>
                      <Select.Option value="初中">初中</Select.Option>
                      <Select.Option value="高中">高中</Select.Option>
                      <Select.Option value="中专">中专</Select.Option>
                      <Select.Option value="大专">大专</Select.Option>
                      <Select.Option value="本科">本科</Select.Option>
                      <Select.Option value="硕士">硕士</Select.Option>
                      <Select.Option value="博士">博士</Select.Option>
                    </Select>
                  )}
                </FormItem>
              </Col>

            </Row>
            <Row gutter={4}>
              <Col span={8}>
                <FormItem labelCol={{span: 10}} label="紧急联系人姓名">
                  {form.getFieldDecorator('emergencycontact')(<Input style={{width: 120}} placeholder="请输入"/>)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{span: 10}} label="紧急联系人电话">
                  {form.getFieldDecorator('contactmobile', {
                    rules: [{
                      required: false, message: '请输入电话号码', pattern: /^1\d{10}$/,
                    }],
                  })(<Input style={{width: 120}} placeholder="请输入"/>)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{span: 10}} label="是否有重大病史">
                  {form.getFieldDecorator('medical')(
                    <Select style={{width: 120}} placeholder="请选择">
                      <Select.Option value={0}>否</Select.Option>
                      <Select.Option value={1}>是</Select.Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Card>}

        </TabPane>
        {modalTitle == '修改劳务人员' && <TabPane tab="派工经历" key="2">

        </TabPane>}
        {modalTitle == '修改劳务人员' && <TabPane tab="考勤信息" key="3">

        </TabPane>}
        {modalTitle == '修改劳务人员' && <TabPane tab="工资发放" key="4">

        </TabPane>}
      </Tabs>

      {modalTitle === '自动读卡' && <div style={{marginTop: 15}}>
        <Alert
          message="读卡器信息提示"
          description={autoMessage}
          type="info"
        />
      </div>}
    </Modal>
  );
});

@connect(({laborPerson, loading}) => ({
  laborPerson,
  formValues: laborPerson.formValues,
  loading: loading.models.laborPerson,
}))
@Form.create()
export default class Person extends PureComponent {
  state = {
    modalTitle: '新增劳务人员',
    type: 'add',
    selectedRows: {},
    modalVisible: false,
    autoLoading: false,
    autoMessage: '请等待',
    autoTimer: null,
  };

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'laborPerson/fetch',
      payload: {
        orderByField: 'createTime',
        isAsc: false,
      }
    });
  }

  handleDelete = record => {
    this.props.dispatch({
      type: 'laborPerson/remove',
      payload: record,
      callback: () => {
        message.success('删除劳务人员成功!');
      },
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
    clearInterval(this.state.autoTimer);
  }

  handleAutoAdd = flag => {
    try {
      var ax = new ActiveXObject("IDRCONTROL.IdrControlCtrl.1");
    } catch (e) {
      notification.error({
        message: `操作错误,错误原因: `,
        description: '读卡功能只支持IE浏览器或未安装读卡控件。',
      });
      return
    }

    this.props.dispatch({
      type: 'laborPerson/new',
      payload: {},
      callback: () => {
        this.setState({
          modalTitle: '自动读卡',
          type: 'add',
        });
        this.handleModalVisible(flag)
        if (idCard.InitComm('1001') == 1) {
          this.setState({
            autoLoading: false,
            autoMessage: '身份证读卡器已经准备好,请放入卡片!',
            autoTimer: setInterval(this.autoReadCard, 1500),
          })
        }
      },
    });
  }


  autoReadCard = () => {
    let t = this;
    let result = idCard.ReadCard()
    if (result != '0') {
      this.setState({
        autoLoading: true,
        autoMessage: '身份证认证失败，无身份证或者此身份证已经读过。请重新放置身份证,或者换一张身份证!',
      })
    } else {
      clearInterval(this.state.autoTimer)
      this.setState({
        autoLoading: true,
        autoMessage: '身份证信息已读取,正在保存数据!'
      })

      const formValues = this.copyCard(idCard)

      this.props.dispatch({
        type: 'laborPerson/add',
        payload: formValues,
        callback: () => {
          this.props.dispatch({
            type: 'laborPerson/new',
            payload: formValues,
            callback: () => {
              this.setState({
                autoLoading: false,
                autoMessage: '身份证数据保存成功,即将重新读取!'
              })
            }
          });
        }
      });

      setTimeout(function () {
        if (idCard.InitComm('1001') == 1) {
          t.props.dispatch({
            type: 'laborPerson/new',
            payload: {},
            callback: () => {
              t.setState({
                autoLoading: true,
                autoMessage: '身份证读卡器已经准备好,请放入卡片!',
                autoTimer: setInterval(t.autoReadCard, 1500),
              })
            }
          });
        }
      }, 2000)
    }
  }

  copyCard = (idCard) => {
    return {
      name: idCard.Name,
      sex: parseInt(idCard.Sex),
      nation: idCard.Nation,
      idtype: 0,
      idnum: idCard.CardNo,
      address: idCard.Address,
      fzjg: idCard.IssuedAt,
      birthday: moment(idCard.Born, 'YYYY-MM-DD'),
      yxq: moment(idCard.ExpiredDate, 'YYYY-MM-DD'),
      fzrq: moment(idCard.EffectedDate, 'YYYY-MM-DD'),
      avatar: idCard.Picture,
    };
  }


  handleReadCard = () => {
    try {
      var ret = idCard.ReadCard();
      if (ret == "0") {
        const formValues = this.copyCard(idCard)
        this.props.dispatch({
          type: 'laborPerson/new',
          payload: formValues,
        });

      } else {
        notification.error({
          message: `读卡错误,错误原因: `,
          description: ret,
        });
      }
    } catch (err) {
      notification.error({
        message: `读卡错误,错误原因: `,
        description: '读卡功能只支持IE浏览器,请用IE浏览器打开此系统。',
      });
    }
  }

  handleNewAdd = flag => {
    this.props.dispatch({
      type: 'laborPerson/new',
      payload: {},
      callback: () => {
        this.setState({
          autoLoading: false,
          modalTitle: '新增劳务人员',
          type: 'add',
        });
        this.handleModalVisible(flag)
      },
    });
  };

  handleEdit = (flag, id) => {
    this.props.dispatch({
      type: 'laborPerson/get',
      payload: id,
      callback: () => {
        this.setState({
          modalTitle: '修改劳务人员',
          type: 'eidt',
        });
        this.handleModalVisible(flag)
      },
    });
  };

  onModelChange = changedFields => {
    this.props.dispatch({
      type: 'laborPerson/change',
      payload: {
        ...changedFields,
      }
    })
  }

  handleAdd = fields => {
    if (this.state.type == 'add') {
      this.props.dispatch({
        type: 'laborPerson/add',
        payload: {
          ...fields,
        },
        callback: () => {
          this.setState({
            modalVisible: false,
          });
          message.success('添加劳务人员成功!');
        },
      });
    } else {
      this.props.dispatch({
        type: 'laborPerson/edit',
        payload: {
          ...fields,
        },
        callback: () => {
          this.setState({
            modalVisible: false,
          });
          message.success('更新劳务人员成功!');
        },
      });
    }
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = {...obj};
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.orderByField = `${sorter.field}`
      if (sorter.order === 'ascend') {
        params.isAsc = true
      } else if (sorter.order === 'descend') {
        params.isAsc = false
      }
    }

    dispatch({
      type: 'laborPerson/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'laborPerson/fetch',
      payload: {},
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'laborPerson/fetch',
        payload: values,
      });
    });
  };


  render() {
    const {laborPerson: {data, formValues}, loading} = this.props;
    const {modalTitle, modalVisible, selectedRows, autoMessage, autoLoading} = this.state;
    const {getFieldDecorator} = this.props.form;
    const columns = [
      {
        title: '序号',
        dataIndex: 'key',
        render: (val, record, index) => (data.pagination.current - 1) == 0 ? 1 + index : (data.pagination.current - 1) * data.pagination.pageSize + 1 + index
      },
      {
        title: '姓名',
        dataIndex: 'name',
        sorter: true,
      },
      {
        title: '证件类型',
        dataIndex: 'idtype',
        render: val => val === 0 ? '身份证' : '',
      },
      {
        title: '证件编号',
        dataIndex: 'idnum',
      },
      {
        title: '性别',
        dataIndex: 'sex',
        render: val => val === 1 ? '男' : '女',

      },
      {
        title: '出生日期',
        dataIndex: 'birthday',
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD')}</span>,
      },
      {
        title: '手机号码',
        dataIndex: 'mobile',
      },
      {
        title: '学历',
        dataIndex: 'education',
        sorter: true,
      },
      {
        title: '当前工种',
        dataIndex: 'worktype',
      },
      {
        title: '创建日期',
        dataIndex: 'createTime',
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this.handleEdit(true, record.id)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否要删除此行？" onConfirm={() => this.handleDelete(record)}>
              <a>删除</a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      onModelChange: this.onModelChange,
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleReadCard: this.handleReadCard,
    };

    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <object id="idCard" height="0" width="0"
                  classID="clsid:10946843-7507-44FE-ACE8-2B3483D179B7" name="idCard"></object>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}><Form onSubmit={this.handleSearch} layout="inline">
              <Row gutter={{md: 8, lg: 24, xl: 48}}>
                <Col md={4} sm={4}>
                  <FormItem label="姓名">
                    {getFieldDecorator('name')(
                      <Input placeholder="请输入姓名查询"/>
                    )}
                  </FormItem>
                </Col>
                <Col md={4} sm={4}>
                  <FormItem labelCol={{span: 9}} wrapperCol={{span: 15}} label="性别">
                    {getFieldDecorator('sex')(
                      <Select placeholder="请选择">
                        <Option value="1">男</Option>
                        <Option value="0">女</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col md={6} sm={6}>
                  <FormItem label="出生日期">
                    {getFieldDecorator('birthday')(
                      <DatePicker placeholder="请选择"/>
                    )}
                  </FormItem>
                </Col>
                <Col md={3} sm={3}>
                  <span className={styles.submitButtons}>
                    <Button type="primary" htmlType="submit">
                      查询
                    </Button>
                    <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                      重置
                    </Button>
                  </span>
                </Col>
              </Row>
            </Form>
            </div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleNewAdd(true)}>
                新建
              </Button>
              <Button icon="plus" onClick={() => this.handleAutoAdd(true)}>
                自动读卡
              </Button>

              {selectedRows.length > 0 && (
                <span>
                     <Button>批量删除</Button>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              rowKey="id"
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm modalTitle={modalTitle} autoMessage={autoMessage} autoLoading={autoLoading}
                    formValues={formValues} {...parentMethods} modalVisible={modalVisible}/>
      </PageHeaderLayout>
    );
  }
}
